<template>
  <el-space direction="vertical">
    <h1>新增</h1>

    <el-form ref="formRef" :model="model" :rules="rules" label-width="100">
      <el-form-item label="标题" prop="title">
        <el-input v-model="model.title" placeholder="请输入标题" />
      </el-form-item>

      <el-form-item label="正文" prop="content">
        <!-- <el-input v-model="model.content" type="textarea" :rows="5" placeholder="请输入正文" /> -->

        <WangEditor v-model="model.content" />
      </el-form-item>

      <el-form-item>
        <el-space>
          <el-button type="default" @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </el-space>
      </el-form-item>
    </el-form>
  </el-space>
</template>

<script lang="ts" setup>
import axios from 'axios'
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import WangEditor from '@/components/wang-editor.vue'
import router from '@/router'

const formRef = ref<FormInstance | null>(null)
const model = reactive({
  title: '',
  content: ''
})

const rules = {
  title: [{ required: true, message: '请输入标题' }],
  content: [{ required: true, message: '请输入正文' }]
}

/**
 * 取消
 */
function handleCancel() {
  router.back()
}

/**
 * 确定
 */
function handleConfirm() {
  formRef.value?.validate((flag) => {
    if (!flag) return

    // 接口调用
    axios.post('http://127.0.0.1:3000/news', model).then(() => {
      ElMessage.success('新增成功')
      router.back()
    })
  })
}
</script>
